﻿using D.UtilCore.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace D.UtilCore.Filters
{
    /// <summary>
    /// 异步异常处理
    /// </summary>
    public class ExtExceptionAsyncFilterAttbute : Attribute, IAsyncExceptionFilter
    {

        private readonly ILogger _logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="loggerFactory"></param>
        public ExtExceptionAsyncFilterAttbute(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<ExtExceptionAsyncFilterAttbute>();
        }

        public async Task OnExceptionAsync(ExceptionContext context)
        {

            // 未经处理的异常
            if (!context.ExceptionHandled)
            {
                _logger.LogCritical(context.Exception, context.ActionDescriptor.DisplayName);
                var content = JsonSerializer.Serialize(new ApiResult<int>()
                {
                    Code =  StatusCodeEnum.Error,
                    Msg = "系统异常"
                });

                context.Result = new ContentResult
                {
                    Content = content,
                    StatusCode = 500,
                    ContentType = "application/json; charset=utf-8"
                };

                context.ExceptionHandled = true;
            }
            else
            {
                _logger.LogError(context.Exception, context.ActionDescriptor.DisplayName);
            }

            await Task.CompletedTask;
        }
    }
}
